﻿using RestSharp;
using System;
using Newtonsoft.Json;
using System.Collections.Generic;
using Common;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using Models.DataBase;

namespace MainService
{
  public class AuthService : IAuthService
  {
    public readonly IAccountService _accountService;

    public AuthService(IAccountService accountService)
    {
      _accountService = accountService;
    }

    public BaseReturn<Account> CreateId(ParmGenToken model)
    {
      var item = new Account()
      {
        Gid = PublicTool.NewGuid(),
        Wid = model.Wid,
        Name = model.Name,
        Roles = JsonConvert.SerializeObject(model.Roles),
        Phone = model.Phone,
        CreateTime = DateTime.Now
      };

      var res = _accountService.AddItem(item);

      return new BaseReturn<Account> { Data = res };
    }

    public BaseReturn<Account> GenToken(string wid)
    {

      var account = _accountService.GetAccountByWid(wid);
      if (account == null) return new BaseReturn<Account>
      {
        Success = false,
        ErrMsg = "未绑定的微信号",
        Data = new Account()
      };

      var Claims = new ClaimsIdentity();
      Claims.AddClaim(new Claim(ClaimTypes.Name, account.Name));

      List<string> roles = JsonConvert.DeserializeObject<List<string>>(account.Roles);
      foreach (string role in roles)
      {
        Claims.AddClaim(new Claim(ClaimTypes.Role, role));
      }

      var tokenHandler = new JwtSecurityTokenHandler();
      var key = Encoding.ASCII.GetBytes("Security:Tokens:Key");
      var tokenDescriptor = new SecurityTokenDescriptor
      {
        Issuer = "Security:Tokens:Issuer",
        Audience = "Security:Tokens:Audience",
        Subject = Claims,
        //Expires = DateTime.UtcNow.AddSeconds(10),
        Expires = DateTime.UtcNow.AddDays(7),
        SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256)
      };

      var _securityToken = tokenHandler.CreateToken(tokenDescriptor);
      var token = tokenHandler.WriteToken(_securityToken);
      account.Token = token;
      return new BaseReturn<Account> { Data = account };
    }

    public OpenIdOfWxOpen GetOpenId(string codes, string encryptedDataStr, string iv)
    {
      var appid = MpToken.AppId;
      var secret = MpToken.AppSecret;
      var api = "https://api.weixin.qq.com/sns/jscode2session?";
      var url = $"{api}appid={appid}&secret={secret}&js_code={codes}&grant_type=authorization_code";

      var client = new RestClient(url);
      client.Timeout = -1;
      var request = new RestRequest(Method.GET);
      IRestResponse response = client.Execute(request);

      var res = JsonConvert.DeserializeObject<OpenIdOfWxOpen>(response.Content);

      return res;
    }

    public string GetPhoneNum(string code)
    {
      var token = MpToken.AccessToken;
      var api = "https://api.weixin.qq.com/wxa/business/getuserphonenumber";
      var url = $"{api}?access_token={token}";
      var client = new RestClient(url);
      client.Timeout = -1;
      var request = new RestRequest(Method.POST);
      request.AddHeader("Content-Type", "application/json");
      var _body = new Dictionary<string, string> { ["code"] = code };
      var body = JsonConvert.SerializeObject(_body);

      request.AddParameter("application/json", body, ParameterType.RequestBody);
      IRestResponse response = client.Execute(request);
      var _res = (Newtonsoft.Json.Linq.JArray)JsonConvert.DeserializeObject($"[{response.Content}]");
      return _res[0]["phone_info"]["phoneNumber"].ToString();
    }
  }
}
